<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NEllipsis,
  NFlex,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NPopconfirm, NSelect,
  NSwitch,
  NTag,
  useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import {router} from "@/router";
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"
import Info from './info.vue'

defineOptions({ name: '会员管理' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  modalAction,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '会员',
  initForm: {},
  doCreate: api.createCustomer,//接口地址修改
  doUpdate: api.updateCustomer,//接口地址修改
  doDelete: api.deleteCustomer,//接口地址修改
  refresh: () => $table.value?.handlerefresh(),
})

const data = reactive({
  platform_options: [
    { label: '小程序', value: 1 },
    { label: 'IOS', value: 2 },
    { label: '安卓', value: 3 },
  ],
  sex_options: [
    { label: '男', value: 1 },
    { label: '女', value: 2 },
  ],
  customer_level: [],
  token: getToken(),
  uploadAction: base_path+'api/customer/users/file',
  onLevelData: [],
  selectValue:'',
  show_excel:false,
  show_info:false,
  select_customer:[],
  CityData: [],
  loading:false,
});

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}


const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

onMounted(() => {
  getcosutomer_level()
  $table.value?.handleSearch()
  api.getSpaceList().then((res) => {
    data.CityData = res.data
  })
})

//表单规则部分
const addAPIRules = {
  name: [
    {
      required: true,
      message: '请输入会员昵称',
      trigger: ['input', 'blur'],
    },
  ],
  role_id: [
    {
      required: true,
      message: '请选择会员级别',
      trigger: ['blur', 'change'],
      type: 'number',
    },
  ],
  phone: [
    {
      required: true,
      message: '请输入联系电话',
      trigger: ['blur', 'change'],
    },
  ],
  birth: [
    {
      required: true,
      message: '请选择会员级别',
      trigger: ['blur', 'change'],
      type: 'date',
    },
  ],
  sex: [
    {
      required: true,
      message: '请选择会员级别',
      trigger: ['blur', 'change'],
      type: 'number',
    },
  ],
}


function show_info(row){
  data.show_info = true
  data.select_customer = row
}

//table表头
const columns = [
  {
    title: 'ID',
    key: 'id',
    align: 'center',
    width: '70',
    ellipsis: { tooltip: true },
  },
    {
    title: '卡号',
    key: 'card_no',
    align: 'center',
    width: '70',
    ellipsis: { tooltip: true },
  },
  {
    title: '头像/昵称',
    key: 'avatar',
    width: '150',
    align: 'left',
    ellipsis: { tooltip: true },
    fixed: 'left',
    render(row) {

      return h(NFlex, {},
        [h(NAvatar, {
          src: row.avatar,
          fallbackSrc: default_image,
          round: true,
          size: "medium",
        }), h(NButton, {
          size: "medium",
          dashed: true,
          type: "primary",
          onClick: () => {
          // 点击事件处理逻辑
            show_info(row)
        }
        }, {
          default: () => (row.name)
        })]
      )

    },
  },
  {
    title: '所属门店',
    key: 'space_name',
    width: 'auto',
    align: 'center',

  },

  {
    title: '会员级别',
    key: 'role_name',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
  },
  // {
  //   title: '真实姓名',
  //   key: 'alias',
  //   width: 'auto',
  //   align: 'center',
  //   ellipsis: { tooltip: true },
  // },
  {
    title: '电话',
    key: 'phone',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  // {
  //   title: '上级',
  //   key: 'parent_data.name',
  //   width: 'auto',
  //   align: 'center',
  //   ellipsis: { tooltip: true },
  // },
  // {
  //   title: '上级卡号',
  //   key: 'parent_data.card_no',
  //   width: 'auto',
  //   align: 'center',
  //   ellipsis: { tooltip: true },
  // },
  {
    title: '性别',
    key: 'sex_name',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  // {
  //   title: '生日',
  //   key: 'birth',
  //   width: 'auto',
  //   align: 'center',
  //   ellipsis: { tooltip: true },
  // },
    {
    title: '注册时间',
    key: 'created_at',
    width: '200',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  //   {
  //   title: '最近登录',
  //   key: 'last_login',
  //   width: '200',
  //   align: 'center',
  //   ellipsis: { tooltip: true },
  // },
  {
    title: '禁用',
    key: 'is_active',
    width: '100',
    align: 'center',
    fixed: 'right',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.is_active,
        loading: !!row.publishing,
        checkedValue: false,
        uncheckedValue: true,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '员工账号',
    key: 'is_user',
    width: '100',
    align: 'center',
    fixed: 'right',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: !row.is_user,
        loading: !!row.publishing,
        checkedValue: false,
        uncheckedValue: true,
        onUpdateValue: () => handleUpdateUser(row),
      })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: '200',
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                handleEdit(row)
                modalForm.value.roles = row.roles.map((e) => (e = e.id))
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          [[vPermission, 'post/api/customer/users/update']]
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ id: row.id }, false),
            onNegativeClick: () => { },
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                [[vPermission, 'delete/api/customer/users/delete']]
              ),
            default: () => h('div', {}, '确定删除该数据吗?'),
          }
        ),
      ]
    },
  },
]

//上传头像
const message = useMessage();

const customRequestMethod = (options) => {
  const { file } = options.file;
  const formData = new FormData();
  formData.append('file', file);
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.code == 200) {
        modalForm.value.avatar = data.data.url
        message.success('文件上传成功');
        options.onProgress(data);
      }else{
           message.error(data.msg);
      }
    })
};
// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.is_active = row.is_active === false ? true : false
  row.publishing = false
  try {
    await api.updateCustomer(row)
    $message?.success(row.is_active ? '已取消禁用该用户' : '已禁用该用户')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.is_active = row.is_active === false ? true : false
  } finally {
    row.publishing = false
  }
}

async function handleUpdateUser(row) {
  if (!row.id) return
  row.publishing = true
  row.is_user = row.is_user === false
  row.publishing = false
  try {
    await api.updateCustomer(row)
    $message?.success(row.is_user ? '已设置为员工': '已取消')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.is_user = row.is_user === false
  } finally {
    row.publishing = false
  }
}

//获取默认会员类型
async function getcosutomer_level() {
  let ret = await api.getCustomerLevel()
  data.customer_level = ret.data
}

async function getspace_list() {
   api.getSpaceList().then((res) => (data.CityData = res.data))
  data.space_list = ret.data
}

//异步下拉获取上级
const optionsRef = ref([]);
const handleLeves = (query) => {

  if (!query.length) {
    data.options = [];
    return;
  }
  data.loading = true;
  window.setTimeout(async () => {
    await api.getSaasUserList({
      name: query
    }).then((res) => {
      data.onLevelData = res.data
    })
    data.loading = false;
  }, 1e3);
}

async function  on_excel(){
   await api.onCustomerExcel({start_time:queryItems.value.start_time,end_time:queryItems.value.end_time})
   data.show_excel = true
   //$message?.success('正在生成下载文件,请前往下载中心查看')
}
function go_excel(){
  router.push({ path: '/downloads/list' });
}

function customer_add(){
  handleAdd()
  modalForm.value.space_id = data.CityData[0].value
}

</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="会员列表">
    <template #action>
      <div>
<!--        <NButton v-permission="'get/api/customer/users/excel'" class="float-right" type="primary" @click="on_excel">-->
<!--          <TheIcon icon="material-symbols:timeline" :size="18" class="mr-5" />导出-->
<!--        </NButton>-->
        <NButton  v-permission="'post/api/customer/users/create'"  class="float-right mr-15" type="primary" @click="customer_add">
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />注册新会员
        </NButton>
      </div>
    </template>
    <!-- 表格 -->
    <CrudTable ref="$table" v-model:query-items="queryItems" :columns="columns" :get-data="api.getCustomer"
      :scroll-x="1600" >
      <template #queryBar>
        <QueryBarItem label="会员昵称" :label-width="70">
          <NInput v-model:value="queryItems.name" clearable type="text" placeholder="请输入会员姓名"
            @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
        <QueryBarItem label="会员卡号" :label-width="70">
          <NInput v-model:value="queryItems.card_no" clearable type="text" placeholder="请输入卡号"
            @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
        <QueryBarItem label="会员类型" :label-width="70">
          <NSelect
            v-model:value="queryItems.role_id"
            style="width: 150px"
            :options="data.customer_level"
            clearable
            placeholder="请选会员类型"
          />
        </QueryBarItem>
        <QueryBarItem label="上级昵称" :label-width="70">
          <NInput v-model:value="queryItems.parent_name" clearable type="text" placeholder="请输入上级姓名"
            @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
        <QueryBarItem label="上级卡号" :label-width="70">
          <NInput v-model:value="queryItems.parent_card_no" clearable type="text" placeholder="请输入上级卡号"
            @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
        <QueryBarItem label="手机号码" :label-width="70">
          <NInput v-model:value="queryItems.phone" clearable type="text" placeholder="请输入手机号"
            @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
        <QueryBarItem label="创建时间" :label-width="70">
          <NDatePicker
            v-model:value="datetimeRange"
            type="datetimerange"
            clearable
            placeholder="请选择时间范围"
            @update:value="handleDateRangeChange"
          />
        </QueryBarItem>
      </template>
    </CrudTable>

    <!-- 新增/编辑 弹窗 -->
    <CrudModal v-model:visible="modalVisible" :title="modalTitle" :loading="modalLoading"
      style="width: 750px !important;" @save="handleSave">

      <NForm ref="modalFormRef" label-placement="left" label-align="left" :label-width="80" :model="modalForm"
        :rules="addAPIRules" :validate-on-rule-change="true">
        <NFlex justify="space-between">
          <NAvatar size="large" round
            :src="modalForm.avatar" :fallbackSrc="default_image">
          </NAvatar>
          <NFormItem path="avatar">
            <NUpload :action="data.uploadAction" :headers="{ token: data.token }" :max="1"
              :custom-request="customRequestMethod" style="margin-right: 505px;" :show-file-list=false>
              <NButton>上传头像</NButton>
            </NUpload>
          </NFormItem>
          <NFormItem label="平台名称" path="platform">
            <NSelect style="width: 200px; " v-model:value="modalForm.platform"
              :options="data.platform_options" placeholder="请输入平台名称" />
          </NFormItem>
          <NFormItem label="会员昵称" path="name">
            <NInput style="width: 200px; " v-model:value="modalForm.name" clearable placeholder="请输入昵称" />
          </NFormItem>
          <NFormItem label="会员卡号" path="card_no">
            <NInputNumber style="width: 200px;" v-model:value="modalForm.card_no" disabled clearable placeholder="系统自动生成" />
          </NFormItem>
          <NFormItem label="所属门店" path="space_id">
            <NSelect style="width: 200px; " v-model:value="modalForm.space_id"
              :options="data.CityData" placeholder="请选择所属门店" />
          </NFormItem>
          <NFormItem label="会员级别" path="role_id">
            <NSelect style="width: 200px; " v-model:value="modalForm.role_id"
              :options="data.customer_level" placeholder="请输入会员级别" />
          </NFormItem>
          <NFormItem label="真实姓名" path="alias">
            <NInput style="width: 200px; " v-model:value="modalForm.alias" clearable placeholder="请输入真实姓名" />
          </NFormItem>
          <NFormItem  label="联系电话" path="phone">
            <NInput style="width: 200px; " v-model:value="modalForm.phone" clearable placeholder="请输入联系电话" />
          </NFormItem>
          <NFormItem label="联系地址" path="address">
            <NInput style="width: 200px; " v-model:value="modalForm.address" clearable placeholder="请输入联系地址" />
          </NFormItem>
          <NFormItem label="会员生日" path="birth">
            <n-date-picker type="date" v-model:formatted-value="modalForm.birth"  value-format="yyyy-MM-dd" placeholder="请输入生日" />
<!--            <NInput style="width: 200px; " v-model:value="modalForm.birth" clearable placeholder="请输入生日" />-->
          </NFormItem>
          <NFormItem label="会员性别" path="sex">
            <NSelect style="width: 200px; " v-model:value="modalForm.sex" :options="data.sex_options"
              placeholder="请输入性别" />
          </NFormItem>
          <NFormItem label="身份证号" path="identity">
            <NInput style="width: 200px; " v-model:value="modalForm.identity" clearable placeholder="请输入身份证号" />
          </NFormItem>

          <NFormItem label="上级选择" path="parent">
            <!-- <NInputNumber style="width: 200px;" v-model:value="modalForm.parent" clearable placeholder="请输入会员级别" /> -->
            <n-select style="width: 200px;" v-model:value="modalForm.parent" filterable placeholder="请输入昵称搜索"
              :options="data.onLevelData" :loading="data.loading" clearable remote @search="handleLeves" />
          </NFormItem>
          <NFormItem label="会员年龄" path="age">
            <NInputNumber style="width: 200px;"  v-model:value="modalForm.age" clearable placeholder="请输入年龄" />
          </NFormItem>
          <NFormItem v-if="modalAction==='add'" label="储值金" path="price">
            <NInputNumber style="width: 200px;"  v-model:value="modalForm.price" clearable placeholder="请输入储值金" />
          </NFormItem>
          <NFormItem v-if="modalAction==='add'" label="赠送金额" path="zs_price">
            <NInputNumber style="width: 200px;"  v-model:value="modalForm.zs_price" clearable placeholder="请输入赠送金额" />
          </NFormItem>
          <NFormItem label="备注信息" path="remark">
            <NInput style="width: 590px;" type="textarea" v-model:value="modalForm.remark" clearable
              placeholder="请输入备注" />
          </NFormItem>
        </NFlex>
      </NForm>

    </CrudModal>
    <!-- 导出模态框 -->
    <n-modal
      v-model:show="data.show_excel"
      preset="dialog"
      title="导出提示..."
      content="导出文件正在生成中,是否前去下载中心下载"
      positive-text="立即查看"
      negative-text="过会再去"
      @positive-click="go_excel"
      @negative-click="cancelCallback"
    />


    <n-drawer v-model:show="data.show_info" width="70%" placement="right">
        <Info :info-data="data.select_customer"/>
    </n-drawer>

  </CommonPage>
</template>
